package com.kitty.game.neidan.service;

import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.message.RespSyncMessage;
import com.kitty.game.hunpo.message.StringIntValue;
import com.kitty.game.neidan.message.ReqNeidanBreakTask;
import com.kitty.game.neidan.message.RespNeidanPanelData;
import com.kitty.game.neidan.model.NeidanProp;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class NeidanService {

    @Autowired
    private RoleService roleService;

    private static final String FULL_STAGE_MSG = "听闻#Y%s#n内丹突破圆满，真是我中州不可多得的人才！#3m";
    private static final String UP_STAGE_MSG = "听闻#Y%s#n内丹突破至#R%s阶#n，真是我中州不可多得的人才！#3m";

    //升级所需积分
    public static final Map<Integer, Integer> UP_REQUIRE_MAP = new HashMap<>();
    //属性map
    public static final Map<Integer, List<StringIntValue>> PROP_MAP = new HashMap<>();
    @Autowired
    RedisService redisService;

    public void loadWuhun(){
        //阶段 影响系数
        float param = 1.0f;
        for (int i = 0; i < 5; i++) {
            int s = i + 1;
            List<StringIntValue> stage = new ArrayList<>();
            stage.add(new StringIntValue("attrib", Math.round(param * s * Integer.parseInt(DataCache.REDIS_DATA.get("neidan_jiacheng_1").toString()))));
            stage.add(new StringIntValue("polar", Math.round(param * s * Integer.parseInt(DataCache.REDIS_DATA.get("neidan_jiacheng_2").toString()))));
            PROP_MAP.put(s, stage);
        }
        //十阶
        int subScore = Integer.parseInt(DataCache.REDIS_DATA.get("neidan"));
        for (int i = 0; i < 5; i++) {
            int s = i + 1;
            double value = Math.round(subScore * Math.pow(2, i));//内丹消耗 第一节 500*4.5  第二节 500*2*4.5
            value = value * 4.5;
            UP_REQUIRE_MAP.put(s, (int) value);
        }
    }
    public void openPanel(Role role) {

        RespNeidanPanelData respNeidanPanelData = getPanelPropResp(role);//获取下一阶段信息

        roleService.sendUpdateNeiDanStage(role,this.getNeidanProp(role));//更新当前阶段
        //内丹属性显示
        MessagePusher.pushMessage(role, respNeidanPanelData);
    }
    public int getNextAttrinPoint(int state,String type){
        List<StringIntValue> stringIntValues = PROP_MAP.get(state);
        for (StringIntValue stringIntValue : stringIntValues) {
            if(stringIntValue.getPropName().equals(type)){
                return stringIntValue.getPropValue();
            }
        }
        return 0;
    }
    /**
     * 获取下一阶段信息
     * @param role
     */
    public RespNeidanPanelData getPanelPropResp(Role role) {
        NeidanProp neidanProp=role.getExtendBox().getNeidanProp();//获得当前阶段信息
        if(neidanProp == null ){
            neidanProp=this.getNeidanProp(role);
        }
        neidanProp.setExp( role.getActivity().getRechargeScore());
        RespNeidanPanelData neidanData=new RespNeidanPanelData();
        neidanData.setIsTop((byte) 0);
        if(neidanProp.getState() == 5 ){
            neidanData.setNxState((byte) 5);
            if(neidanProp.getStage() == 5){
                neidanData.setIsTop((byte) 1);
                neidanData.setNxStage((byte) 5);
            }else{
                neidanData.setNxStage((byte) ((byte) neidanProp.getStage()+1));
            }
        }else{
            if(neidanProp.getStage() == 5){
                neidanData.setNxState((byte) ((byte) neidanProp.getState()+1));
                neidanData.setNxStage(((byte) 1));
            }else{
                neidanData.setNxState(((byte) neidanProp.getState()));
                neidanData.setNxStage((byte) ((byte) neidanProp.getStage()+1));
            }
        }
        neidanData.setNxAttribPoint((short) getNextAttrinPoint(neidanData.getNxState(),"attrib"));
        neidanData.setNxPolarPoint((short) getNextAttrinPoint(neidanData.getNxState(),"polar"));
        return neidanData;
    }

    private Object getNeiDanProp(Role role) {
        return null;
    }

    public void breakTask(Role role, ReqNeidanBreakTask request) {

        NeidanProp neidanProp = this.getNeidanProp(role);
        //看当前需要的精气
        int req = this.getJqUpReq(neidanProp.getState(), neidanProp.getStage());

        //role.getActivity().setRechargeScore(role.getActivity().getRechargeScore()-req);

        String subType = DataCache.REDIS_DATA.get("neidao_xiaohao");
        roleService.subCountByteType(role,req, subType);
//        if (req > neidanProp.getExp()) {
//            //精气不够
//            MessagePusher.pushMessage(role, new RespMsg("当前积分不足以提升！"));
//            return;
//        }

        if (neidanProp.getState() * 5 + neidanProp.getStage()  >= 30) {
            MessagePusher.pushMessage(role, new RespMsg("已无法再突破！"));
            return;
        }

        RespSyncMessage respSyncMessage = new RespSyncMessage();
        respSyncMessage.setCode((short) 20481);

        if(neidanProp.getStage() >=5){
            neidanProp.setStage(1);
            neidanProp.setState(neidanProp.getState()+1);
            if(neidanProp.getState()>5){
                neidanProp.setState(5);
                neidanProp.setStage(5);
                String msg = String.format(FULL_STAGE_MSG, role.getName());
                SpringUtils.getBroadcastService().sendRumor(msg, null);
            }else {
                if (neidanProp.getState()>3){
                    String msg = String.format(UP_STAGE_MSG, role.getName(), neidanProp.getState());
                    SpringUtils.getBroadcastService().sendRumor(msg, null);
                }
                neidanProp.setStage(1);
            }
        }else {
            neidanProp.setStage(neidanProp.getStage()+1);
            log.error("玩家{} 悟道升小段{}", role.getUid(), neidanProp.getState());
        }

        neidanProp.setExpToNextLevel(this.getJqUpReq(neidanProp.getState(),neidanProp.getStage()));

        role.getExtendBox().setNeidanProp(neidanProp);



        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMiscEx(
                "你消耗了#R" + req + "#n积分成功突破圆满!")));



        //杂项
        MessagePusher.pushMessage(role, respSyncMessage);

        //弹窗
        MessagePusher.pushMessage(role, new RespMsg("恭喜，突破成功！"));

        this.calcAddedProp(neidanProp);

        role.setLastAttrib(roleService.getLastAttributePoint(role));
        role.setLastPolar(roleService.getLastPolarPoint(role));
        role.save();
        //这三个包缺一不可，顺序也不能错
        //发送属性
        roleService.sendExtraAttribute(role);
        //更新内丹当前阶段
        roleService.sendUpdateNeiDanStage(role,neidanProp);

        //更新面板
        this.updateNextStatePanel(role);

    }

    private void updateNextStatePanel(Role role) {
        RespNeidanPanelData respNeidanPanelData = getPanelPropResp(role);//获取下一阶段信息
        MessagePusher.pushMessage(role, respNeidanPanelData);

    }

    private void calcAddedProp(NeidanProp neidanProp) {
        int totalPolar= neidanProp.getTotalPolarPoint();
        int totalArrtibute= neidanProp.getTotalAttribPoint();
        List<StringIntValue> stringIntValues = PROP_MAP.get(neidanProp.getState());
        for (StringIntValue stringIntValue : stringIntValues) {
            if("attrib".equals(stringIntValue.getPropName())){
                totalArrtibute+=stringIntValue.getPropValue();
            }
            if("polar".equals(stringIntValue.getPropName())){
                totalPolar += stringIntValue.getPropValue();
            }
        }
        neidanProp.setTotalPolarPoint(totalPolar);
        neidanProp.setTotalAttribPoint(totalArrtibute);
    }


    private int getJqUpReq(int state, int stage) {
        return UP_REQUIRE_MAP.getOrDefault(state, 500);
    }

    /**
     [439] = "dan_data/state",
     [440] = "dan_data/stage",
     [441] = "dan_data/exp",
     [442] = "dan_data/exp_to_next_level",
     [443] = "dan_data/attrib_point",
     [444] = "dan_data/polar_point",
     [445] = "not_check_bw",
     [446] = "has_break_lv_limit",
     [447] = "dan_data/today_exp",
     */



    public NeidanProp getNeidanProp(Role role) {
        NeidanProp neidanProp = role.getExtendBox().getNeidanProp();

        if (neidanProp == null) {
            //数据初始化
            neidanProp = new NeidanProp();
            neidanProp.setState(1);
            neidanProp.setStage(1);
            neidanProp.setExpToNextLevel(200);
            neidanProp.setTodayExp(300);
            neidanProp.setAttribPoint(0);//内丹的 属性点修改
            neidanProp.setPolarPoint(0);//内丹的相性点修改
            neidanProp.setExp(role.getActivity().getRechargeScore());
            role.getExtendBox().setNeidanProp(neidanProp);
            role.save();
        }else{
            //neidanProp.setState(1);
           // neidanProp.setStage(1);
            //neidanProp.setExpToNextLevel(100);
            //neidanProp.setTodayExp(100);
            neidanProp.setExp(role.getActivity().getRechargeScore());
            role.save();
        }
        return neidanProp;
    }

}
